<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    :showFooter="true"
    v-bind="$attrs"
    :title="getTitle.value"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="90%"
  >
    <BasicForm @register="registerForm">
      <template #cxfpList>
        <BasicTable @register="registercxfpTable" @row-click="handlecxfpRowClick">
          <!-- @edit-change="rowChange" :expandedRowKeys="expands" -->
          <template #toolbar>
            <a-button type="primary" @click="handleAdjust({})">
              <Icon icon="ant-design:clock-circle-outlined" /> {{ t('批量计划调整') }}
            </a-button>
          </template>
          <template #fpTextarea="{ record: childRecord }">
            <a-textarea v-model:value="childRecord.textContent" placeholder="请输入" :rows="5" />
          </template>
          <!-- <template #expandedRowRender="{ record }">
        <div >
          <div style="padding: 20px;background: #fff;" >
            <a-table
              :columns="tableColumns"
              :data-source="record.dataSource"
              :pagination="false"
              :bordered="true"
            >
              <template  #bodyCell="{ record, index, column }">
                <template v-if="column.dataIndex == 'iqty'">
                  <a-input v-model:value="record[column.dataIndex]" style="text-align: center" type="number"/>
                </template>
              </template>
            </a-table>
          </div>
        </div>
      </template> -->

          <template #lineCode="{ record }">
            <TreeSelect
              v-model:value="record.lineCode"
              :api="basLineListTreeData"
              :params="{
                isShowCode: true,
                isAll: true,
                'basWorkShop.officeId': record.workShopCode,
              }"
              :canSelectParent="false"
              placeholder="请选择"
              :treeCheckable="false"
              :immediate="true"
            />
          </template>
          <template #teamCode="{ record }">
            <TreeSelect
              v-model:value="record.teamCode"
              :api="basTeamListTreeData"
              :params="{
                isShowCode: true,
                'workShop.officeCode': record.workShopCode,
              }"
              :canSelectParent="false"
              placeholder="请选择"
              :treeCheckable="false"
              :immediate="true"
            />
          </template>
        </BasicTable>
      </template>
    </BasicForm>
    <AdjustModal2 @register="registerModal" @modifyDate="modifyDate" />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMoOrderScOrderCxfpForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  // import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  // import { ScOrder, scOrderAdjust } from '/@/api/mes/mo/order/scOrder';
  import {
    MesOrderLinefp,
    mesOrderLinefpLineFp,
    mesOrderLinefpLineFp2,
  } from '/@/api/mes/mo/line/mesOrderLinefp';

  import { BasicTable, useTable } from '/@/components/Table';
  import { basLineListTreeData } from '/@/api/bas/mes/workline/basLine';
  import { basTeamListTreeData } from '/@/api/bas/mes/team/basMesTeam';
  import AdjustModal2 from './adjustForm2.vue';
  import { useModal } from '/@/components/Modal';
  import { TreeSelect } from '/@/components/Form';
  // import { InputTextArea } from '/@/components/Form';

  const emit = defineEmits(['success', 'register']);

  let expands = ref<any>([]);

  const { t } = useI18n('mo.order.scOrder');
  const { showMessage } = useMessage();
  const record = ref<MesOrderLinefp>({} as MesOrderLinefp);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: t('产线分配'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      // label: t('计划开始'),
      field: 'cxfp',
      component: 'Input',
      slot: 'cxfpList',
    },
  ];

  const [registerForm, { validate, resetFields }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registercxfpTable, cxfpTable] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record: Recordable) => [
    //     {
    //       icon: 'ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handleTestDataChildDelete.bind(this, record),
    //       },
    //       auth: 'test:testData:edit',
    //     },
    //   ],
    // },
    rowKey: 'id',
    pagination: false,
    // expandRowByClick: true,
    bordered: true,
    // size: 'small',
    inset: true,
    ellipsis: false,
    defaultExpandAllRows: true,
  });

  const tableColumns: BasicColumn[] = [
    {
      title: t('生产线'),
      dataIndex: 'lineCode',
      width: 200,
      align: 'center',
    },
    {
      title: t('数量'),
      dataIndex: 'iqty',
      width: 80,
      align: 'center',
      editRow: true,
      editComponent: 'Input',
      editRule: true,
    },
  ];

  const [registerModal, { openModal }] = useModal();

  const [registerDrawer, { closeDrawer, setDrawerProps }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    // await cxfpTable.setTableData([]);
    // await resetFields();
    console.log(data, 'data===');
    record.value.arr = data.arr.map((item) => {
      item.textContent = '';
      item.lineCode = '';
      item.taskPleNum = '';
      item.ziqty = item.iqty;
      item.iqty = item.syQty;
      item.scOrder = {
        planStartDateWork: item.planStartDateWork,
        planOverDateWork: item.planOverDateWork,
      };
      item.dataSource = [];
      return item;
    });
    record.value.__t = new Date().getTime();
    setcxfpChildTableData(record.value);
    setDrawerProps({ loading: false });
  });

  async function setcxfpChildTableData(_res: Recordable) {
    cxfpTable.setColumns([
      {
        title: t('订单号'),
        dataIndex: 'code',
        width: 80,
        align: 'left',
        fixed: 'left',
      },
      {
        title: t('订单行号'),
        dataIndex: 'sortNum',
        width: 60,
        align: 'left',
        fixed: 'left',
      },
      {
        title: t('存货编码'),
        dataIndex: 'invCode',
        width: 80,
        align: 'left',
        fixed: 'left',
      },
      {
        title: t('存货名称'),
        dataIndex: 'basInv.cinvname',
        width: 200,
        align: 'left',
        fixed: 'left',
      },
      {
        title: t('规格型号'),
        dataIndex: 'basInv.cinvstd',
        width: 200,
        align: 'left',
      },
      {
        title: t('订单数'),
        dataIndex: 'ziqty',
        // key: 'a.iqty',
        // sorter: true,
        width: 50,
        align: 'center',
      },
      {
        title: t('待分配数'),
        dataIndex: 'syQty',
        // key: 'a.iqty',
        // sorter: true,
        width: 70,
        align: 'center',
      },
      {
        title: t('预计完成时间(分)'),
        dataIndex: 'proTakeTime',
        width: 80,
        align: 'center',
      },
      {
        title: t('换产时间(秒)'),
        dataIndex: 'proChangeTime',
        width: 80,
        align: 'center',
      },
      {
        title: t('计划开始(时间)'),
        dataIndex: 'scOrder.planStartDateWork',
        width: 160,
        align: 'center',
        editRow: true,
        editable: true,
        editComponent: 'DatePicker',
        editComponentProps(props) {
          return {
            format: 'YYYY-MM-DD HH:mm',
            showTime: { format: 'HH:mm' },
            valueFormat: 'YYYY-MM-DD HH:mm',
            onOk(date, dateString) {
              const dateIime = new Date(date);
              const dd = dateIime.setTime(dateIime.getTime() + props.record.proTakeTime * 60000);
              const resultDate = new Date(dd).toLocaleString().replace(/\//g, '-');
              props.record.scOrder.planOverDateWork = resultDate;

              console.log('dateIime', resultDate);
            },
          };
        },
        editRule: true,
      },
      {
        title: t('计划结束(时间)'),
        dataIndex: 'scOrder.planOverDateWork',
        width: 160,
        align: 'center',
        editRow: true,
        editable: true,
        editComponent: 'DatePicker',
        // editComponentProps: {
        //   format: 'YYYY-MM-DD HH:mm',
        //   showTime: { format: 'HH:mm' },
        //   valueFormat: 'YYYY-MM-DD HH:mm',
        // },
        editComponentProps(props) {
          return {
            format: 'YYYY-MM-DD HH:mm',
            showTime: { format: 'HH:mm' },
            valueFormat: 'YYYY-MM-DD HH:mm',
            onOk(date, dateString) {
              const dateIime = new Date(date);
              const dd = dateIime.setTime(dateIime.getTime() - props.record.proTakeTime * 60000);
              const resultDate = new Date(dd).toLocaleString().replace(/\//g, '-');
              props.record.scOrder.planStartDateWork = resultDate;
            },
          };
        },
        editRule: true,
      },

      // {
      //   title: t('产线分配'),
      //   dataIndex: 'textContent',
      //   width: 130,
      //   align: 'left',
      //   slot: 'fpTextarea',
      // },
      {
        title: t('产线分配'),
        dataIndex: 'lineCode',
        // dataLabel: 'lineName',
        width: 130,
        align: 'left',
        // editRow: true,
        // editable: true,
        // editComponent: 'TreeSelect',
        // editComponentProps: {
        //   api: basLineListTreeData,
        //   params: { isShowCode: true, isAll: true },
        //   canSelectParent: false,
        //   allowClear: true,
        //   // treeCheckable: true,
        //   // immediate: true,
        // },
        // editRule: true,
        slot: 'lineCode',
      },
      {
        title: t('班组分配'),
        dataIndex: 'teamCode',
        width: 130,
        align: 'left',
        slot: 'teamCode',
      },
      {
        title: t('分配数'),
        dataIndex: 'iqty',
        width: 80,
        align: 'center',
        editRow: true,
        editable: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          allowClear: true,
        },
        editRule: true,
      },
      // {
      //   title: t('操作工人数'),
      //   dataIndex: 'taskPleNum',
      //   width: 80,
      //   align: 'center',
      //   editRow: true,
      //   editable: true,
      //   editComponent: 'InputNumber',
      //   editComponentProps: {
      //     allowClear: true,
      //   },
      //   editRule: false,
      // },
    ]);
    cxfpTable.setTableData(record.value.arr || []);
  }

  function handlecxfpRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  async function getCxfpTableChildList() {
    let cxfpTableChildListValid = true;
    let cxfpTableChildList: Recordable[] = [];
    for (const record of cxfpTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        cxfpTableChildListValid = false;
      }
      cxfpTableChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of cxfpTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      cxfpTableChildList.push({
        ...record,
        status: '1',
      });
    }
    if (!cxfpTableChildListValid) {
      throw { errorFields: [{ name: ['cxfpTableChildList'] }] };
    }
    return cxfpTableChildList;
  }

  async function handleAdjust() {
    openModal(true, {});
  }

  async function modifyDate(data) {
    for (const record of cxfpTable.getDataSource()) {
      record.scOrder = data.scOrder;
      const dateIime = new Date();
      const dd = dateIime.setTime(dateIime.getTime() + record.proTakeTime * 60000);
      const resultDate = new Date(dd).toLocaleString().replace(/\//g, '-');
      data.scOrder.planOverDateWork = resultDate;
      record.scOrder = data.scOrder;
      console.log(data, 'data');
      console.log(record, 'record');
    }
  }

  async function handleSubmit() {
    try {
      // const data = await validate();
      // data.selIds = record.value.selIds;
      setDrawerProps({ confirmLoading: true });
      const data = {};
      data.list = await getCxfpTableChildList();

      data.list.forEach((item) => {
        // item.lineCode = item.editValueRefs.lineCode;
        item.iqty = item.editValueRefs.iqty;
        item.taskPleNum = item.editValueRefs.taskPleNum;
        item.scOrder = {
          planStartDateWork: item.editValueRefs['scOrder,planStartDateWork'],
          planOverDateWork: item.editValueRefs['scOrder,planOverDateWork'],
        };
      });
      //console.log('submit', data);
      const res = await mesOrderLinefpLineFp2(data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
  async function rowChange({ column, value, record }) {
    if (column.dataIndex == 'lineCode') {
      if (!expands.value.includes(record.id)) {
        expands.value.push(record.id);
      }
      record.dataSource = [];
      record.lineCode = value;
      console.log(value, 'value====');
      if (value) {
        let arr = value.split(',');
        if (arr.length == 1) {
          record.dataSource = [
            {
              lineCode: value,
              iqty: record.syQty,
            },
          ];
        } else {
          arr.forEach((item) => {
            record.dataSource.push({
              lineCode: item,
              iqty: '',
            });
          });
        }
      } else {
        record.dataSource = [];
      }
    }
  }
</script>
<style lang="less" scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }

  /* .jeesite-editable-cell__action {
    display: none;
  } */

  :deep(.edit-cell-align-center) {
    width: 100% !important;
  }
</style>
